<template>
  <div class="card-setting-container" v-loading="loading">
    <!--start 新建附加组件 -->
    <div class="card-setting-heard">
      <div class="card-setting-title">
        <h2>{{$t('task.setting.additionalSettings')}}</h2>
        <el-button type="primary" :loading="false" @click="onClickCreateHandler"><i class="iconfont icon-add2"></i>{{$t('common.base.addModule', {module: ''})}}</el-button>
      </div>
      <div class="card-setting-msg">
        {{$t('task.setting.taskTypeSetting.flow.tabs.title1')}}
        <el-tooltip placement="top" popper-class="card-display-tooltip" >
          <div slot="content">
            <template>
              <div class="card-displaymode--item">{{$t('task.setting.taskTypeSetting.flow.tabs.title2')}}</div>
              <div class="card-displaymode-item">{{$t('task.setting.taskTypeSetting.flow.tabs.title3')}}</div>
            </template>
          </div>
          <i class="iconfont icon-question"></i>
        </el-tooltip>
      </div>
    </div>
    <!--end 新建附加组件 -->

    <!--start 附加组件列表 -->
    <div class="card-setting-list" v-if="taskCardList.length > 0">
      <draggable
        v-bind="dragOptions"
        v-model="taskCardList"
        tag="div"
        @change="updateTaskCardOrder"
        class="task-card-group"
      >
        <task-card-item
          class="task-card-item"
          v-for="(item, idx) in taskCardList"
          :key="item.id"
          :index="idx"
          :task-card="taskCardList[idx]"
          :task-type-id="taskTypeId"
          :taskTypeName="taskTypeName"
          @finish="fetchTaskType"
          @deleteCard="deleteCard"
          @edit="onEditConnectorCardHandler"
          @updateAttr="obj => {
            updateTaskCard(item, obj)
        }">
        </task-card-item>
      </draggable>
    </div>
    <!--end 附加组件列表 -->

    <!-- start 无数据 -->
    <no-data-view-new
      v-else
      :notice-msg="$t('task.setting.taskTypeSetting.flow.tabs.tip1')"
    ></no-data-view-new>
    <!-- end 无数据 -->

    <!-- start 新建附加组件 -->
    <creat-card-dialog
      :visiable.sync="isShowAddCardModal"
      @onClose="onCloseShowAddCardModal"
      :task-card-list="taskCardList"
      @update="update"
      @updateImport="updateImport"
    ></creat-card-dialog>
    <!-- end 新建附加组件 -->
    
    <!-- start 新建附加组件或连接器弹窗 -->
    <ConnectorModuleAddCardDialog
      :visible="isShowNewCreateCardModal"
      @cardCreate="onCardCreateHandler"
      @connectorCreate="onConnectorCreateHandler"
      @close="onCloseNewCreateCardModal"
    />
    <!-- end 新建附加组件或连接器弹窗 -->
    
    <!-- start 连接器新建弹窗 -->
    <ConnectorModuleCreateConnectorDialog
      v-if="taskTypeId"
      :title="connectorCreateModalTitle"
      :visible="isShowCreateConnectorModal"
      :bizTypeId="bizTypeId"
      :toBizType="toBizType"
      :fromBizType="fromBizType"
      :fromBizTypeName="fromBizTypeName"
      isShowSelectLanguage
      @close="onCloseCreateConnectorModal"
      @finish="finishFetchTaskType"
    />
    <!-- end 连接器新建弹窗 -->
    
    <!-- start 编辑连接器弹窗 -->
    <ConnectorModuleEditConnectorDialog
      :title="connectorEditModalTitle" 
      :fromBizTypeName="fromBizTypeName"
      :visible="isShowEditConnectorModal"
      :connectorInfo="connectorInfo"
      @close="onCloseEditConnectorModal"
      @finish="fetchTaskType"
    />
    <!-- end 编辑连接器弹窗 -->
    
  </div>
</template>
<script>
import draggable from 'vuedraggable';
// utils
import { parse } from '@src/util/querystring';
import { logDataToParams } from '../util';
import { getAllGrayInfo } from '@src/util/grayInfo';
import { TaskFlowMap } from 'src/modules/setting/task/taskTypeSetting/flow/util/FlowNewNodeMixin.js'
import { isEmpty } from 'pub-bbx-utils'
// api
import * as TaskApi from '@src/api/TaskApi.ts';
import * as SettingTaskApi from '@src/api/SettingTaskApi';
// component 
import TaskCardItem from '../components/TaskCardItem';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import CreatCardDialog from '../components/TaskCard/CreatCardDialog';

import { ConnectorModuleAddCardDialog } from '@src/modules/connector'
import { ConnectorModuleCreateConnectorDialog } from '@src/modules/connector/components'

import _, { cloneDeep } from 'lodash';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import { getRootWindow } from '@src/util/dom'
/* mixin */
import { ConnectorModuleCardSettingTaskMixin, ConnectorModuleCardSettingMixin } from '@src/modules/connector'

export default {
  name: 'card-setting-panel',
  mixins: [ConnectorModuleCardSettingTaskMixin, ConnectorModuleCardSettingMixin],
  props: {
    taskTypeName: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      loading: true,
      taskTypeId: '',
      taskCardList: [],
      authInfo:[],
      oldCardInfo: [],
      flowsInfo: [],
    };
  },
  computed: {
    dragOptions() {
      return {
        animation: 380, 
        ghostClass: 'ghost'
      };
    },
    // 是否开启了流程节点灰度
    isOpenTaskFlowExtend() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
    },
  },
  async mounted() {
    let query = parse(window.location.search) || {};
    this.taskTypeId = query.taskTypeId;
    this.fetchTaskType();
    this.getRoleListReq();
  },
  activated() {
    this.fetchTaskType();
    if(this.isOpenTaskFlowExtend) this.getTaskFlowNode()
  },
  methods: {
    goBack() {
      let fromId = window.frameElement.getAttribute('fromid');
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
      
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskTypeManage,
        titleKey: this.$t('task.setting.taskFlowSettings'),
        reload: true,
        fromId
      })
    },
    async getTaskFlowNode() {
      try {
        const params = {
          taskId: '',
          taskTypeId: this.taskTypeId
        }
        const { result = [] } = await SettingTaskApi.getTaskFlowNode(params);
        this.flowsInfo = result;
      } catch (e) {
        console.error(e)
      }
    },
    // 保存节点信息（保存节点的附加组件）
    async saveTaskFlowNode() {
      try {
        if(isEmpty(this.flowsInfo)) return;

        let flows = _.cloneDeep(this.flowsInfo)

        // 处理附加组件数据
        flows = flows?.map(item => {
          const key = item?.type === 'normal' ? item.id : (TaskFlowMap?.[item.type] ?? item.type)
          let commonNodeCardIds = []
          this.taskCardList?.forEach(card => {
            if(card.stateCanEdit?.includes(key)) {
              commonNodeCardIds.push(card.id)
            }
          })
          this.$set(item.data, 'commonNodeCardIds', commonNodeCardIds)
          return item;
        })

        const params = {
          taskTypeId: this.taskTypeId,
          nodeList: flows,
        }

        await SettingTaskApi.createTaskFlowNode(params);

      } catch (e) {
        console.error(e)
      }
    },

    /** 
     * @description 保存数据
     * @param {object} otherParams 工单类型名称和颜色
     * @param {boolean} flag 是否返回上一页
     */
    async submit(otherParams, flag) {

      // 调用保存节点接口去保存附加组件，但是不能影响后面的接口
      try {
        this.isOpenTaskFlowExtend && await this.saveTaskFlowNode();
      }catch (e) {
        console.error(e)
      }

      try {
        // 附加组件权限设置 更改设置权限的方式 authInfo需传空或不传 
        const objectIds = [];
        this.taskCardList.forEach(x => {
          x.authInfo = [];
          if(x.isSetObject === 'add') { // add添加 set设置过使用权限的
            objectIds.push(x.id);
            delete x.isSetObject;
          }
        });

        const params = {
          taskTypeId: this.taskTypeId,
          cardInfo: this.taskCardList,
          ...otherParams
        }
        let res = await SettingTaskApi.batchSaveTaskCard(params); 
        if(res.status === 0) {
          SettingTaskApi.initDefaultTaskRange({
            taskTypeId: this.taskTypeId,
            objectIds
          })
          .then(() => {})
          .catch(e => console.log('SettingTaskApi.initDefaultTaskRange: ', e))

          this.$platform.notification({
            title: this.$t('common.base.saveSuccess'),
            type: 'success'
          });
          // 运营需求，去掉跳转
          // if(flag) {
          //   setTimeout(()=>{
              
          //     this.goBack();
          //   }, 1000)
          // }
          this.$customerOperateLog(logDataToParams('card',{taskTypeName: otherParams.name,taskCardList: this.taskCardList, oldCardInfo: this.oldCardInfo}));//记录用户操作日志
        }else {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
    deleteCard(index) {
      this.taskCardList.splice(index, 1);
      this.$platform.notification({
        title: this.$t('common.base.deleteSuccess'),
        type: 'success'
      });
    },
    updateTaskCard(cardList, updateObj) {
      for (const key in updateObj) {
        if (updateObj.hasOwnProperty(key)) {
          cardList[key] = updateObj[key];
        }
      }
    },
    // 获取角色列表
    getRoleListReq() {
      SettingTaskApi.getRoleList({pageSize:0})
        .then((res) => {
          const { status, message, list } = res;
          
          list.forEach(element => {
            let obj = {}
            obj.canRead = true;
            obj.canWrite = true;
            obj.canCreate = true;
            obj.canDelete = true;
            obj.id = element.id;
            obj.name = element.name;
            this.authInfo.push(obj)
            
          });  
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 从已添加的组件库选择
    update(newCard) {

      let list = [];
      const oldList = cloneDeep(this.taskCardList);
      const cardIdMap = new Map();
      newCard.forEach(item=>{
        cardIdMap.set(item.id, item)
      })
      oldList.forEach(item=>{ // 保留原数据
        if(cardIdMap.has(item.id)){
          list.push(item);
          cardIdMap.delete(item.id)
        }
        if(item.type === 8) {
          // 这里还需要添加上已经的连接器附加组件
          list.push(item);
        }
      });
      let newList = [...cardIdMap.values()];
      newList = newList.map(item=>Object.assign(item, {notNullFlow: null, stateCanEdit: null, authInfo:this.authInfo, isSetObject: 'add'}))
      list.push(...newList);
      this.taskCardList = list;
      this.onCloseShowAddCardModal();

      const newCardName = newList.map(item => item.name).join(',');
      this.$track.clickStat(this.$track.formatParams('CREATE_COMP_SUCCESS', newCardName));
    },

    // 从模版库中选择更新数据
    updateImport(newCard){
      this.$track.clickStat(this.$track.formatParams('CREATE_COMP_SUCCESS', newCard.name));

      let newTaskCard = Object.assign(newCard, {notNullFlow: null, stateCanEdit: null, authInfo:this.authInfo, isSetObject: 'add'});
      this.taskCardList.push(newTaskCard);
      this.onCloseShowAddCardModal();
    },

    // 工单类型附加组件排序 order重新排序
    updateTaskCardOrder(data){
      this.taskCardList.forEach((item, idx) => {
        item.order = idx + 1;
      })
    },   
    /**
     * 获取工单设置的除组件外的其他信息
     */
    async fetchTaskType() {
      try {
        const { status, message, data } = await TaskApi.getTaskType({ id: this.taskTypeId});
        this.loading = false;
        if( status == 0 ){
          if(JSON.stringify(data.cardSetting) !== '{}' && data.cardSetting.cardInfo){
            this.taskCardList = data.cardSetting.cardInfo;
            this.oldCardInfo = cloneDeep(data.cardSetting.cardInfo)
          }
        }     
      } catch (err) {
        console.error('fetch Tasktype => err', err);
        this.loading = false;
      }
    },
    // 检查内容是否有修改 (暴露的方法)
    checkModified() {
      return JSON.stringify(this.taskCardList) != JSON.stringify(this.oldCardInfo)
    },
    // 同步初始数据 (暴露的方法) 
    resetInit() {
      this.taskCardList = cloneDeep(this.oldCardInfo);
    },
    // 查询最新添加的连接器数据
    async finishFetchTaskType(){
      const oldTaskType = cloneDeep(this.taskCardList);
      await this.fetchTaskType();
      // 查找当前添加的连接器附加组件
      const item = this.taskCardList.find(x => !oldTaskType.some(v => v.id === x.id)) || {};
      if(Object.keys(item).length !== 0) {
        item.isSetObject = 'add';
        oldTaskType.push(item);
      }
      this.taskCardList = oldTaskType;
    },
  },
  components: {
    [TaskCardItem.name]: TaskCardItem,
    [NoDataViewNew.name]: NoDataViewNew,
    [CreatCardDialog.name]: CreatCardDialog,
    draggable,
  }
};
</script>
<style lang="scss" scoped>
.card-setting-container {
  min-height: calc(100vh - 48px);
  overflow-y: auto;
  .card-setting-heard {
    font-weight: 500;
    color: #333333;
    font-size: 16px;
    background: #fff;
    padding: 12px;
    .card-setting-title {
      display: flex;
      justify-content: space-between;
      position: relative;
      h2 {
        margin-right: 16px;
        margin-bottom: 0;
        color: #333333;
        font-size: 16px;
        margin-bottom: 8px;
      }
      button {
        position: absolute;
        right: 0;
        padding: 8px 15px;
      .iconfont{
        font-size: 14px;
        margin-right: 8px;
      }
      }
    }
    .card-setting-msg {
      font-size: 12px;
      color: #666666;
      line-height: 20px;
      .el-tooltip{
        font-size: 12px;
        color: #999;
      }
    }
  }
  .card-setting-list{
    margin: 12px;
    .task-card-group{
      display: flex;
      flex-flow: wrap;
      min-height: 300px;
      width: calc(100% + 12px);

      .task-card-item{
        margin: 0 12px 12px 0;
      }
    }
  }
}
.card-display-tooltip{
  span{
    width: 8px;
    height: 8px;
  }
}

// transtion
.flip-list-move {
  transition: transform 0.5s;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
</style>
